package com.demo.spark.rdd;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;

import java.util.*;

public class RddAggregateMax {
    public static void main(String[] args) {

        SparkConf sparkConf = new SparkConf();
        sparkConf.setAppName("rdd count by key");
        sparkConf.setMaster("local");
        JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf);
        javaSparkContext.setLogLevel("error");

        List<Integer> data = Arrays.asList(5, 1, 1, 4, 4, 2, 2);
        JavaRDD<Integer> javaRDD = javaSparkContext.parallelize(data,3);
        JavaRDD<String> stringJavaRDD = javaRDD.mapPartitionsWithIndex(new Function2<Integer, Iterator<Integer>, Iterator<String>>() {
            @Override
            public Iterator<String> call(Integer v1, Iterator<Integer> v2) throws Exception {
                LinkedList<String> linkedList = new LinkedList<String>();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("partition_"+v1+",data : ");
                while (v2.hasNext()) {
                    Integer next = v2.next();
                    stringBuffer.append(next+",");
                }
                linkedList.add(stringBuffer.toString());
                return linkedList.iterator();
            }
        },false);
        List<String> collect = stringJavaRDD.collect();
        for (String s : collect) {
            System.out.println(s);
        }
        Integer aggregateValue = javaRDD.aggregate(0, new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                System.out.println("seq~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + v1 + "," + v2);
                return Math.max(v1, v2);
            }
        }, new Function2<Integer, Integer, Integer>() {
            int i = 0;
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                System.out.println("comb~~~~~~~~~i~~~~~~~~~~~~~~~~~~~"+i++);
                System.out.println("comb~~~~~~~~~v1~~~~~~~~~~~~~~~~~~~" + v1);
                System.out.println("comb~~~~~~~~~v2~~~~~~~~~~~~~~~~~~~" + v2);
                return Math.max(v1, v2);
            }
        });
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+aggregateValue);

        /*
        模拟求最大值
        1.分区内求最大值
        2.跟上一个分区求得的值进行比较，求得最大值
        3.第一个分区求得组内最大值后，也会跟0值进行一次比较，就想组内的第一个值跟0值进行比较一样，所以0值可以设置成理想的初始值
         */

    }
}
